package org.wlldTest.lesson8;

import org.dromara.easyai.i.CustomEncoding;
import org.dromara.easyai.matrixTools.Matrix;

import java.util.Map;
import java.util.Random;

/**
 * @author lidapeng
 * @time 2025/4/12 20:50
 */
public class Server implements CustomEncoding {
    private static Matrix featureMatrix;
    private float allError1 = 0;
    private float allError2 = 0;
    private int backNumber = 0;
    private float studyRate = 0.00001f;

    public Server() throws Exception {
        Random random = new Random();
        featureMatrix = new Matrix(2, 2);
        int x = featureMatrix.getX();
        int y = featureMatrix.getY();
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                featureMatrix.setNub(i, j, random.nextFloat());
            }
        }
    }

    public Matrix getFeatureMatrix(int id) throws Exception {
        return featureMatrix.getRow(id - 1);
    }

    @Override
    public void backError(Map<Integer, Float> map, int i) {
        backNumber++;
        float error1 = map.get(3);
        float error2 = map.get(4);
        allError1 = allError1 + error1;
        allError2 = allError2 + error2;
        if (backNumber == 3) {
            backNumber = 0;
            float sub1 = allError1 * studyRate;
            float sub2 = allError2 * studyRate;
            for (int k = 0; k < 2; k++) {
                float value;
                if (k == 0) {
                    value = sub1;
                } else {
                    value = sub2;
                }
                for (int l = 0; l < 2; l++) {
                    try {
                        float nextValue = featureMatrix.getNumber(k, l) + value;
                        featureMatrix.setNub(k, l, nextValue);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            allError1 = 0;
            allError2 = 0;
        }
    }


}
